<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>ClickHouse-MySQL同步工具</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        :root {
            --primary-color: #3498db;
            --secondary-color: #2ecc71;
            --accent-color: #e74c3c;
            --light-bg: #f8f9fa;
            --dark-bg: #343a40;
        }

        body {
            background-color: #f5f7fa;
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }

        .main-card {
            border-radius: 15px;
            overflow: hidden;
            box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
            border: none;
        }

        .card {
            border-radius: 10px;
            border: none;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            transition: transform 0.2s ease, box-shadow 0.2s ease;
        }

        .card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 15px rgba(0, 0, 0, 0.1);
        }

        .card-header {
            border-bottom: none;
            font-weight: 600;
        }

        .dashboard-header {
            background: linear-gradient(135deg, var(--primary-color), #4a69bd);
            color: white;
            padding: 20px 30px;
        }

        .status-indicator {
            padding: 15px 20px;
            border-radius: 10px;
            background-color: rgba(255, 255, 255, 0.9);
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
        }

        .btn {
            border-radius: 8px;
            font-weight: 500;
            padding: 10px 20px;
            transition: all 0.3s ease;
        }

        .btn-primary {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .btn-success {
            background-color: var(--secondary-color);
            border-color: var(--secondary-color);
        }

        .btn-danger {
            background-color: var(--accent-color);
            border-color: var(--accent-color);
        }

        .btn-outline-primary {
            color: var(--primary-color);
            border-color: var(--primary-color);
        }

        .form-control,
        .form-select {
            border-radius: 8px;
            border: 1px solid #e1e5eb;
            padding: 10px 15px;
        }

        .table {
            border-radius: 10px;
            overflow: hidden;
        }

        .table thead th {
            background-color: #f8f9fa;
            border-bottom: none;
            font-weight: 600;
        }

        .status-badge {
            display: inline-block;
            padding: 6px 12px;
            border-radius: 20px;
            font-weight: 500;
            font-size: 0.875rem;
        }

        .status-badge.not-init {
            background-color: #f1f2f6;
            color: #7f8c8d;
        }

        .status-badge.running {
            background-color: #e3f9e5;
            color: #27ae60;
        }

        .status-badge.error {
            background-color: #fae3e3;
            color: #e74c3c;
        }
    </style>
</head>

<body>
    <div class="container py-5">
        <div class="row justify-content-center">
            <div class="col-12 col-xl-10">
                <div class="main-card card">
                    <div class="dashboard-header">
                        <div class="d-flex justify-content-between align-items-center mb-4">
                            <h2 class="mb-0"><i class="bi bi-database-fill-gear me-2"></i>ClickHouse-MySQL同步工具</h2>
                            <a href="config.html" class="btn btn-light btn-sm">
                                <i class="bi bi-gear-fill me-1"></i>配置设置
                            </a>
                        </div>

                        <div class="status-indicator">
                            <div class="d-flex justify-content-between align-items-center">
                                <div>
                                    <div class="text-muted mb-1">同步状态</div>
                                    <div class="d-flex align-items-center">
                                        <div class="status-badge not-init" id="sync-status-badge">未初始化</div>
                                        <span class="ms-3 text-dark" id="sync-status">未初始化</span>
                                    </div>
                                </div>
                                <div>
                                    <span class="text-muted me-2">上次更新:</span>
                                    <span id="last-update" class="text-primary fw-medium">-</span>
                                    <button class="btn btn-sm btn-outline-secondary ms-2" id="btn-refresh-status"
                                        title="刷新状态">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="card-body p-4">
                        <div class="row g-4 mb-4">
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-light py-3">
                                        <h5 class="mb-0"><i class="bi bi-info-circle me-2"></i>同步配置</h5>
                                    </div>
                                    <div class="card-body">
                                        <div class="mb-3">
                                            <label class="form-label text-muted">同步模式</label>
                                            <div id="sync-mode" class="form-control-plaintext fw-bold">-</div>
                                        </div>
                                        <div class="mb-0">
                                            <label class="form-label text-muted">同步表</label>
                                            <div id="sync-tables-container">
                                                <div id="sync-tables"
                                                    class="form-control-plaintext d-flex flex-wrap gap-2">-</div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <div class="col-md-6">
                                <div class="card h-100">
                                    <div class="card-header bg-light py-3">
                                        <h5 class="mb-0"><i class="bi bi-toggles me-2"></i>操作控制</h5>
                                    </div>
                                    <div class="card-body d-flex align-items-center justify-content-center">
                                        <div class="d-flex flex-column align-items-center gap-3 w-100">
                                            <button id="btn-init" class="btn btn-primary w-75 position-relative">
                                                <i class="bi bi-tools me-2"></i>初始化同步环境
                                                <span
                                                    class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger d-none"
                                                    id="init-badge">
                                                    <i class="bi bi-exclamation-triangle-fill"></i>
                                                    <span class="visually-hidden">需要初始化</span>
                                                </span>
                                            </button>
                                            <button id="btn-start" class="btn btn-success w-75 position-relative"
                                                disabled>
                                                <i class="bi bi-play-fill me-2"></i>开始增量同步
                                                <span class="spinner-border spinner-border-sm text-light d-none"
                                                    id="start-spinner" role="status" aria-hidden="true"></span>
                                            </button>
                                            <button id="btn-stop" class="btn btn-danger w-75 position-relative"
                                                disabled>
                                                <i class="bi bi-stop-fill me-2"></i>停止增量同步
                                                <span class="spinner-border spinner-border-sm text-light d-none"
                                                    id="stop-spinner" role="status" aria-hidden="true"></span>
                                            </button>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <div class="card">
                            <div class="card-header bg-light py-3 d-flex justify-content-between align-items-center">
                                <h5 class="mb-0"><i class="bi bi-arrow-repeat me-2"></i>全量同步</h5>
                                <div class="d-flex align-items-center">
                                    <select id="table-select" class="form-select form-select-sm"
                                        style="width: auto; min-width: 200px;">
                                        <option value="">-- 选择表 --</option>
                                    </select>
                                    <button class="btn btn-sm btn-outline-primary ms-2" id="btn-refresh-tables"
                                        title="刷新表列表">
                                        <i class="bi bi-arrow-clockwise"></i>
                                    </button>
                                </div>
                            </div>
                            <div class="card-body">
                                <div class="d-flex justify-content-center mb-4">
                                    <button id="btn-full-sync" class="btn btn-secondary w-50 position-relative"
                                        disabled>
                                        <i class="bi bi-arrow-clockwise me-2"></i>执行全量同步
                                        <span class="spinner-border spinner-border-sm text-light d-none"
                                            id="full-sync-spinner" role="status" aria-hidden="true"></span>
                                    </button>
                                </div>

                                <div>
                                    <div class="d-flex justify-content-between align-items-center mb-3">
                                        <h6 class="mb-0"><i class="bi bi-table me-2"></i>表结构信息</h6>
                                        <div class="text-muted small" id="table-info">未选择表</div>
                                    </div>
                                    <div class="table-responsive">
                                        <table class="table table-hover border">
                                            <thead class="table-light">
                                                <tr>
                                                    <th>字段名</th>
                                                    <th>MySQL类型</th>
                                                    <th>ClickHouse类型</th>
                                                    <th>可为空</th>
                                                    <th>主键</th>
                                                    <th>注释</th>
                                                </tr>
                                            </thead>
                                            <tbody id="table-schema-body">
                                                <tr>
                                                    <td colspan="6" class="text-center py-4 text-muted">请选择表</td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="alert alert-info d-none" id="sync-result">
                                        <i class="bi bi-info-circle-fill me-2"></i>
                                        <span id="sync-result-message"></span>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 模态框 -->
    <div class="modal fade" id="message-modal" tabindex="-1" data-bs-backdrop="static" aria-labelledby="modal-title"
        aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="modal-title">消息</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="关闭"
                        id="modal-close-btn"></button>
                </div>
                <div class="modal-body" id="modal-body">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-primary" id="modal-ok-btn" data-bs-dismiss="modal">确定</button>
                </div>
            </div>
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js"></script>
    <script src="js/app.js"></script>
    <script>
        // 用于防止MutationObserver递归触发的标志
        let isUpdatingTables = false;
        let isUpdatingStatus = false;
        // 定时刷新状态的计时器ID
        let statusRefreshTimer = null;

        // 为状态徽章添加动态类切换功能
        function updateStatusBadge(status) {
            // 如果已经在更新中，跳过以防止循环
            if (isUpdatingStatus) return;

            isUpdatingStatus = true;
            const badge = document.getElementById('sync-status-badge');
            if (!badge) {
                isUpdatingStatus = false;
                return;
            }

            badge.textContent = status;

            // 移除所有状态类
            badge.classList.remove('not-init', 'running', 'error');

            // 根据状态添加适当的类
            if (status === '未初始化') {
                badge.classList.add('not-init');
                // 显示初始化警告徽章
                const initBadge = document.getElementById('init-badge');
                if (initBadge) initBadge.classList.remove('d-none');
            } else if (status.includes('运行') || status.includes('同步中')) {
                badge.classList.add('running');
                // 隐藏初始化警告徽章
                const initBadge = document.getElementById('init-badge');
                if (initBadge) initBadge.classList.add('d-none');
            } else if (status.includes('错误') || status.includes('失败')) {
                badge.classList.add('error');
                // 根据错误情况决定是否显示初始化警告
                if (status.includes('未初始化') || status.includes('需要初始化')) {
                    const initBadge = document.getElementById('init-badge');
                    if (initBadge) initBadge.classList.remove('d-none');
                }
            } else {
                // 隐藏初始化警告徽章
                const initBadge = document.getElementById('init-badge');
                if (initBadge) initBadge.classList.add('d-none');
            }

            // 解除更新标志
            setTimeout(() => {
                isUpdatingStatus = false;
            }, 0);
        }

        // 处理同步表显示
        function updateSyncTables(tablesText) {
            // 如果已经在更新中，跳过以防止循环
            if (isUpdatingTables) return;

            isUpdatingTables = true;
            const container = document.getElementById('sync-tables');

            // 清空现有内容
            container.innerHTML = '';

            if (!tablesText || tablesText === '-') {
                container.textContent = '-';
                isUpdatingTables = false;
                return;
            }

            // 分割表名并创建徽章
            const tables = tablesText.split(',').map(table => table.trim());

            tables.forEach(table => {
                if (table) {
                    const badge = document.createElement('span');
                    badge.className = 'badge bg-light text-primary border border-primary-subtle rounded-pill';
                    badge.style.padding = '6px 12px';
                    badge.style.fontSize = '0.85rem';
                    badge.innerHTML = `<i class="bi bi-table me-1"></i>${table}`;
                    container.appendChild(badge);
                }
            });

            // 解除更新标志
            setTimeout(() => {
                isUpdatingTables = false;
            }, 0);
        }

        // 刷新同步状态
        function refreshStatus() {
            fetch('/api/sync/status')
                .then(response => response.json())
                .then(data => {
                    if (data.status) {
                        // 更新状态显示
                        document.getElementById('sync-status').textContent = data.status;
                        updateStatusBadge(data.status);

                        // 更新最后刷新时间
                        document.getElementById('last-update').textContent = new Date().toLocaleString();

                        // 根据状态启用/禁用按钮
                        const btnInit = document.getElementById('btn-init');
                        const btnStart = document.getElementById('btn-start');
                        const btnStop = document.getElementById('btn-stop');

                        // 确保按钮存在
                        if (btnInit && btnStart && btnStop) {
                            if (data.status === '增量同步运行中') {
                                btnInit.disabled = true;
                                btnStart.disabled = true;
                                btnStop.disabled = false;
                            } else if (data.status === '未初始化') {
                                btnInit.disabled = false;
                                btnStart.disabled = true;
                                btnStop.disabled = true;
                            } else {
                                btnInit.disabled = false;
                                btnStart.disabled = false;
                                btnStop.disabled = true;
                            }

                            // 确保按钮图标正确显示
                            if (btnInit.innerHTML.includes('spinner')) {
                                btnInit.innerHTML = '<i class="bi bi-tools me-2"></i>初始化同步环境';
                                if (data.status === '未初始化') {
                                    // 显示警告徽章
                                    btnInit.innerHTML += '<span class="position-absolute top-0 start-100 translate-middle badge rounded-pill bg-danger" id="init-badge"><i class="bi bi-exclamation-triangle-fill"></i><span class="visually-hidden">需要初始化</span></span>';
                                }
                            }

                            // 确保开始按钮图标正确
                            if (!btnStart.querySelector('i.bi-play-fill')) {
                                btnStart.innerHTML = '<i class="bi bi-play-fill me-2"></i>开始增量同步<span class="spinner-border spinner-border-sm text-light d-none" id="start-spinner" role="status" aria-hidden="true"></span>';
                            }

                            // 确保停止按钮图标正确
                            if (!btnStop.querySelector('i.bi-stop-fill')) {
                                btnStop.innerHTML = '<i class="bi bi-stop-fill me-2"></i>停止增量同步<span class="spinner-border spinner-border-sm text-light d-none" id="stop-spinner" role="status" aria-hidden="true"></span>';
                            }

                            // 确保开始和停止按钮的spinner正确隐藏
                            const startSpinner = document.getElementById('start-spinner');
                            const stopSpinner = document.getElementById('stop-spinner');

                            if (startSpinner) startSpinner.classList.add('d-none');
                            if (stopSpinner) stopSpinner.classList.add('d-none');
                        }
                    }
                })
                .catch(error => {
                    console.error('刷新状态失败:', error);
                });
        }

        // 定时刷新同步状态
        function startStatusRefresh() {
            // 如果已经有计时器在运行，先清除它
            if (statusRefreshTimer) {
                clearInterval(statusRefreshTimer);
            }

            // 设置30秒自动刷新状态
            statusRefreshTimer = setInterval(refreshStatus, 30000); // 30秒刷新一次
        }

        // 在页面加载时初始化
        document.addEventListener('DOMContentLoaded', function () {
            // 初始状态更新
            updateStatusBadge(document.getElementById('sync-status').textContent);
            updateSyncTables(document.getElementById('sync-tables').textContent);

            // 监听ajax加载的数据
            // 使用一个新的方法来观察DOM变化，减少不必要的更新
            const appJsObserver = new MutationObserver(function (mutations) {
                // 检查是否有同步状态变化
                const statusElement = document.getElementById('sync-status');
                if (statusElement && !isUpdatingStatus) {
                    updateStatusBadge(statusElement.textContent);
                }

                // 检查是否有同步表变化
                const tablesElement = document.getElementById('sync-tables');
                if (tablesElement && !isUpdatingTables && tablesElement.textContent !== '-') {
                    // 只有当内容不是默认值时才更新
                    if (tablesElement.children.length === 0 ||
                        (tablesElement.children.length === 1 && tablesElement.textContent.trim() === '-')) {
                        updateSyncTables(tablesElement.textContent);
                    }
                }
            });

            // 只观察body的变化，性能更好
            appJsObserver.observe(document.body, {
                childList: true,
                subtree: true,
                characterData: true
            });

            // 设置当前时间
            document.getElementById('last-update').textContent = new Date().toLocaleString();

            // 启动自动刷新
            startStatusRefresh();

            // 刷新按钮事件
            document.getElementById('btn-refresh-status').addEventListener('click', function () {
                refreshStatus();
            });

            // 状态指示器点击事件
            document.querySelector('.status-indicator').addEventListener('click', function (e) {
                // 排除刷新按钮本身的点击，避免触发两次
                if (!e.target.closest('#btn-refresh-status')) {
                    refreshStatus();
                }
            });

            // 初始化按钮点击
            document.getElementById('btn-init').addEventListener('click', function () {
                const button = this;
                // 保存按钮内容
                const iconElement = button.querySelector('i.bi');
                const iconClass = iconElement ? iconElement.className : '';
                const buttonText = "初始化同步环境";
                const badgeElement = button.querySelector('span#init-badge');
                const badgeHTML = badgeElement ? badgeElement.outerHTML : '';

                button.disabled = true;
                button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span> 初始化中...';

                fetch('/api/sync/init', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showMessage('成功', data.message);
                            setTimeout(refreshStatus, 1000);
                        } else {
                            showMessage('错误', data.message);
                        }
                    })
                    .catch(error => {
                        console.error('初始化同步环境失败:', error);
                        showMessage('错误', '初始化同步环境失败: ' + error.message);
                    })
                    .finally(() => {
                        // 恢复按钮内容
                        button.disabled = false;
                        button.innerHTML = `<i class="${iconClass}"></i>${buttonText}${badgeHTML}`;
                    });
            });

            // 开始同步按钮点击
            document.getElementById('btn-start').addEventListener('click', function () {
                const button = this;
                const spinner = document.getElementById('start-spinner');

                // 保存图标元素
                const iconElement = button.querySelector('i.bi');
                const iconClass = iconElement ? iconElement.className : '';
                const buttonText = "开始增量同步";

                button.disabled = true;
                if (spinner) spinner.classList.remove('d-none');

                fetch('/api/sync/incremental/start', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showMessage('成功', data.message);
                            setTimeout(refreshStatus, 1000);
                        } else {
                            showMessage('错误', data.message);
                            button.disabled = false;
                            // 确保图标恢复
                            if (!button.querySelector('i.bi') && iconClass) {
                                button.innerHTML = `<i class="${iconClass}"></i>${buttonText}<span class="spinner-border spinner-border-sm text-light d-none" id="start-spinner" role="status" aria-hidden="true"></span>`;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('开始增量同步失败:', error);
                        showMessage('错误', '开始增量同步失败: ' + error.message);
                        button.disabled = false;
                        // 确保图标恢复
                        if (!button.querySelector('i.bi') && iconClass) {
                            button.innerHTML = `<i class="${iconClass}"></i>${buttonText}<span class="spinner-border spinner-border-sm text-light d-none" id="start-spinner" role="status" aria-hidden="true"></span>`;
                        }
                    })
                    .finally(() => {
                        if (spinner) spinner.classList.add('d-none');
                    });
            });

            // 停止同步按钮点击
            document.getElementById('btn-stop').addEventListener('click', function () {
                const button = this;
                const spinner = document.getElementById('stop-spinner');

                // 保存图标元素
                const iconElement = button.querySelector('i.bi');
                const iconClass = iconElement ? iconElement.className : '';
                const buttonText = "停止增量同步";

                button.disabled = true;
                if (spinner) spinner.classList.remove('d-none');

                fetch('/api/sync/incremental/stop', { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            showMessage('成功', data.message);
                            setTimeout(refreshStatus, 1000);
                        } else {
                            showMessage('错误', data.message);
                            button.disabled = false;
                            // 确保图标恢复
                            if (!button.querySelector('i.bi') && iconClass) {
                                button.innerHTML = `<i class="${iconClass}"></i>${buttonText}<span class="spinner-border spinner-border-sm text-light d-none" id="stop-spinner" role="status" aria-hidden="true"></span>`;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('停止增量同步失败:', error);
                        showMessage('错误', '停止增量同步失败: ' + error.message);
                        button.disabled = false;
                        // 确保图标恢复
                        if (!button.querySelector('i.bi') && iconClass) {
                            button.innerHTML = `<i class="${iconClass}"></i>${buttonText}<span class="spinner-border spinner-border-sm text-light d-none" id="stop-spinner" role="status" aria-hidden="true"></span>`;
                        }
                    })
                    .finally(() => {
                        if (spinner) spinner.classList.add('d-none');
                    });
            });

            // 刷新表列表按钮点击
            document.getElementById('btn-refresh-tables').addEventListener('click', function () {
                const button = this;

                // 显示加载效果
                if (button) {
                    const originalHTML = button.innerHTML;
                    button.innerHTML = '<span class="spinner-border spinner-border-sm" role="status" aria-hidden="true"></span>';
                    button.disabled = true;

                    // 1秒后恢复按钮状态
                    setTimeout(() => {
                        button.innerHTML = originalHTML;
                        button.disabled = false;
                    }, 1000);
                }

                // 刷新状态
                refreshStatus();
            });

            // 表选择变更事件
            document.getElementById('table-select').addEventListener('change', function () {
                loadTableSchema();
            });

            // 全量同步按钮点击
            document.getElementById('btn-full-sync').addEventListener('click', function () {
                const tableName = document.getElementById('table-select').value;
                if (!tableName) {
                    showMessage('警告', '请选择要同步的表');
                    return;
                }

                const button = this;
                const spinner = document.getElementById('full-sync-spinner');
                const syncResult = document.getElementById('sync-result');
                const syncResultMessage = document.getElementById('sync-result-message');

                button.disabled = true;

                // 隐藏之前的结果
                if (syncResult) syncResult.classList.add('d-none');

                // 显示加载中动画
                if (spinner) spinner.classList.remove('d-none');

                fetch(`/api/sync/full/${tableName}`, { method: 'POST' })
                    .then(response => response.json())
                    .then(data => {
                        if (data.success) {
                            // 显示成功消息
                            if (syncResult && syncResultMessage) {
                                syncResult.classList.remove('d-none');
                                syncResult.classList.remove('alert-danger');
                                syncResult.classList.add('alert-success');
                                syncResultMessage.textContent = data.message;
                            }
                        } else {
                            // 显示错误消息
                            if (syncResult && syncResultMessage) {
                                syncResult.classList.remove('d-none');
                                syncResult.classList.remove('alert-success');
                                syncResult.classList.add('alert-danger');
                                syncResultMessage.textContent = data.message;
                            }
                        }
                    })
                    .catch(error => {
                        console.error('全量同步失败:', error);
                        // 显示错误信息
                        if (syncResult && syncResultMessage) {
                            syncResult.classList.remove('d-none');
                            syncResult.classList.remove('alert-success');
                            syncResult.classList.add('alert-danger');
                            syncResultMessage.textContent = '全量同步失败: ' + error.message;
                        }
                    })
                    .finally(() => {
                        button.disabled = false;
                        if (spinner) spinner.classList.add('d-none');
                    });
            });

            /**
             * 加载表结构信息
             */
            function loadTableSchema() {
                const tableName = document.getElementById('table-select').value;
                const tableSchemaBody = document.getElementById('table-schema-body');
                const tableInfo = document.getElementById('table-info');
                const btnFullSync = document.getElementById('btn-full-sync');
                const syncResult = document.getElementById('sync-result');

                // 确保所有元素都存在
                if (!tableSchemaBody) return;

                // 隐藏之前的同步结果
                if (syncResult) syncResult.classList.add('d-none');

                if (!tableName) {
                    tableSchemaBody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-muted">请选择表</td></tr>';
                    if (tableInfo) tableInfo.textContent = '未选择表';
                    if (btnFullSync) btnFullSync.disabled = true;
                    return;
                }

                // 更新选中表信息
                if (tableInfo) tableInfo.textContent = `当前选择: ${tableName}`;

                tableSchemaBody.innerHTML = '<tr><td colspan="6" class="text-center py-4"><div class="spinner-border spinner-border-sm" role="status"></div> 加载中...</td></tr>';

                fetch(`/api/sync/table/${tableName}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data && data.columns && tableSchemaBody) {
                            // 启用全量同步按钮
                            if (btnFullSync) btnFullSync.disabled = false;

                            // 显示表结构
                            tableSchemaBody.innerHTML = '';

                            if (data.columns.length === 0) {
                                tableSchemaBody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-muted">该表没有列信息</td></tr>';
                                return;
                            }

                            data.columns.forEach(column => {
                                const row = document.createElement('tr');

                                // 创建单元格并设置内容
                                const nameCell = document.createElement('td');
                                nameCell.textContent = column.name;
                                nameCell.classList.add('fw-medium');

                                const mysqlTypeCell = document.createElement('td');
                                mysqlTypeCell.textContent = column.mysqlType || '-';

                                const clickhouseTypeCell = document.createElement('td');
                                clickhouseTypeCell.textContent = column.clickhouseType || '-';

                                const nullableCell = document.createElement('td');
                                nullableCell.innerHTML = column.nullable ?
                                    '<span class="badge rounded-pill bg-light text-secondary border border-secondary-subtle">可为空</span>' :
                                    '<span class="badge rounded-pill bg-light text-danger border border-danger-subtle">不可为空</span>';

                                const primaryKeyCell = document.createElement('td');
                                primaryKeyCell.innerHTML = column.primaryKey ?
                                    '<span class="badge rounded-pill bg-light text-primary border border-primary-subtle">主键</span>' :
                                    '-';

                                const commentCell = document.createElement('td');
                                commentCell.textContent = column.comment || '-';
                                commentCell.classList.add('text-muted');

                                // 将单元格添加到行
                                row.appendChild(nameCell);
                                row.appendChild(mysqlTypeCell);
                                row.appendChild(clickhouseTypeCell);
                                row.appendChild(nullableCell);
                                row.appendChild(primaryKeyCell);
                                row.appendChild(commentCell);

                                // 将行添加到表体
                                tableSchemaBody.appendChild(row);
                            });
                        } else {
                            if (tableSchemaBody) tableSchemaBody.innerHTML = '<tr><td colspan="6" class="text-center py-4 text-danger">获取表结构失败</td></tr>';
                            if (btnFullSync) btnFullSync.disabled = true;
                        }
                    })
                    .catch(error => {
                        console.error('获取表结构失败:', error);
                        if (tableSchemaBody) tableSchemaBody.innerHTML = `<tr><td colspan="6" class="text-center py-4 text-danger">获取表结构失败: ${error.message}</td></tr>`;
                        if (btnFullSync) btnFullSync.disabled = true;
                    });
            }

            // 初始化一次状态
            refreshStatus();
        });

        // 显示消息模态框
        function showMessage(title, message) {
            const modalTitle = document.getElementById('modal-title');
            const modalBody = document.getElementById('modal-body');
            modalTitle.textContent = title;
            modalBody.textContent = message;

            // 获取模态框元素
            const modalElement = document.getElementById('message-modal');

            // 确保之前的任何遮罩都被清除
            document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
                backdrop.remove();
            });

            // 创建并显示模态框
            const messageModal = new bootstrap.Modal(modalElement);

            // 当模态框隐藏后移除遮罩
            modalElement.addEventListener('hidden.bs.modal', function () {
                document.querySelectorAll('.modal-backdrop').forEach(backdrop => {
                    backdrop.remove();
                });
                // 移除body上的modal-open类
                document.body.classList.remove('modal-open');
                // 移除inline样式
                document.body.style.removeProperty('padding-right');
                document.body.style.removeProperty('overflow');
            }, { once: true }); // 只执行一次

            messageModal.show();
        }
    </script>
</body>

</html>